﻿Public Class frmIncome
    Dim dsIncome As DataSet
    Dim daIncome As OleDb.OleDbDataAdapter
    Dim dsIncRs As DataSet
    Dim daIncRs As OleDb.OleDbDataAdapter
    Dim sql As String
    Dim able1Comma, able2Comma, able3Comma, able4Comma As String

    Private Sub frmIncome_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        e.Cancel = True
        Me.Hide()
    End Sub

    Private Sub frmIncome_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Call gSubIconShow(Me)
        Call initForm()
        Call gSubMkCmbAccount(cmbAccount, "IN")
        Call gSubMkCmbPayMethod(cmbPayMethod)
        Call gSubMkCmbCompany("", cmbCompany)
        Call gSubMkCmbCompany("", cmbFindCompany)

        gSubMkCmbFlag(cmbFlag) '## 삭제 여부 콤보박스 초기화
        cmbFlag.SelectedIndex = 0
        gSubMkCmbFlag(cmbRsFlag) '## 삭제 여부 콤보박스 초기화
        cmbRsFlag.SelectedIndex = 0
        Call grid1Refresh("default")
        Call grid2Refresh("default")
        Call grid3Refresh("default")
    End Sub

    '## 입금 내역 저장하기
    Private Sub btnRsSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRsSave.Click
        Call saveIncRs()
    End Sub

    Private Sub grdSumCompany_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grdSumCompany.CellClick
        If e.RowIndex = -1 Then
            Exit Sub
        End If
        If IsDBNull(grdSumCompany.Rows(e.RowIndex).Cells(0).Value) = True Then
            Exit Sub
        End If

        cmbFindCompany.SelectedValue = grdSumCompany.Rows(e.RowIndex).Cells(0).Value
        Call grid1Refresh("")
    End Sub

    '## 거래내역 입금내역으로 뿌리기
    Private Sub btnSetIncResult_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSetPayResult.Click
        txtRsAmount.Text = txtAmount.Text
        dpActionDt.Text = dpIncomeDt.Text
        dpBankDt.Text = dpIncomeDt.Text
    End Sub

    Private Sub txtFindCompany_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtFindCompany.KeyUp
        Call gSubMkCmbCompany(txtFindCompany.Text, cmbCompany)
    End Sub

    'Private Sub txtFindCompany_Leave(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtFindCompany.Leave
    '    Call gSubMkCmbCompany(txtFindCompany.Text, cmbCompany)
    'End Sub

    Private Sub txtAmount_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtAmount.Leave
        txtOrgAmount.Text = txtAmount.Text
        txtTax.Text = 0
    End Sub

    Private Sub txtAmount_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtAmount.KeyPress
        If Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
            e.Handled = True
            able1Comma = ""
        Else
            able1Comma = "ok"
        End If
    End Sub

    Private Sub txtAmount_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtAmount.KeyUp
        If able1Comma = "ok" Then
            gSubWithComma(txtAmount)
        End If
    End Sub

    Private Sub txtOrgAmount_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtOrgAmount.KeyPress
        If Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
            e.Handled = True
            able2Comma = ""
        Else
            able2Comma = "ok"
        End If
    End Sub

    Private Sub txtOrgAmount_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtOrgAmount.KeyUp
        If able2Comma = "ok" Then
            gSubWithComma(txtOrgAmount)
        End If
    End Sub

    Private Sub txtTax_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtTax.KeyPress
        If Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
            e.Handled = True
            able3Comma = ""
        Else
            able3Comma = "ok"
        End If
    End Sub

    Private Sub txtTax_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtTax.KeyUp
        If able3Comma = "ok" Then
            gSubWithComma(txtTax)
        End If
    End Sub

    Private Sub txtRsAmount_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtRsAmount.KeyPress
        If Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
            e.Handled = True
            able4Comma = ""
        Else
            able4Comma = "ok"
        End If
    End Sub

    Private Sub txtRsAmount_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtRsAmount.KeyUp
        If able4Comma = "ok" Then
            gSubWithComma(txtRsAmount)
        End If
    End Sub

    Private Sub btnSetTax_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSetTax.Click
        Dim valTax As Double
        If txtAmount.Text <> "" Then
            valTax = (CDbl(txtAmount.Text) / 11)
            txtTax.Text = valTax
            txtOrgAmount.Text = CDbl(txtAmount.Text) - CDbl(valTax)
            gSubWithComma(txtTax)
            gSubWithComma(txtOrgAmount)
        End If
    End Sub

    Private Sub btnNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNew.Click
        Call txtReset()
    End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Call saveIncome("showAnswer")
    End Sub

    Private Sub btnAddPay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddPay.Click
        TabControl.SelectedIndex = 1
        Call txtReset()
    End Sub

    Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        Call grid1Refresh("")
    End Sub

    Private Sub btnSearchReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearchReset.Click
        txtSearch.Clear()
        'initForm()
        cmbFindCompany.SelectedValue = 0
        Call grid1Refresh("")
    End Sub

    Private Sub txtSearch_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtSearch.KeyPress
        If Asc(e.KeyChar) = 13 Then
            Call grid1Refresh("")
        End If
    End Sub

    Private Sub btnRsNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRsNew.Click
        Call txtRsReset()
    End Sub

    Private Sub btnAllSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAllSave.Click

        Call saveIncome("allSave")
        txtRsAmount.Text = txtAmount.Text
        dpActionDt.Text = dpIncomeDt.Text
        dpBankDt.Text = dpIncomeDt.Text
        Call saveIncRs()
    End Sub

    Private Sub cmbAccount_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles cmbAccount.KeyPress
        e.Handled = True
    End Sub

    Private Sub cmbCompany_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles cmbCompany.KeyPress
        e.Handled = True
    End Sub

    Private Sub cmbFindCompany_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles cmbFindCompany.KeyPress
        e.Handled = True
    End Sub

    Private Sub cmbFlag_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles cmbFlag.KeyPress
        e.Handled = True
    End Sub

    Private Sub cmbPayMethod_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles cmbPayMethod.KeyPress
        e.Handled = True
    End Sub

    Private Sub cmbRsFlag_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles cmbRsFlag.KeyPress
        e.Handled = True
    End Sub

    Private Sub btnCopyIncome_Click(sender As System.Object, e As System.EventArgs) Handles btnCopyIncome.Click
        Dim isIncome As String
        isIncome = gAFieldValue("SELECT COUNT(*) FROM tblIncome WHERE flag='Y'")
        If isIncome = 0 Then
            MsgBox("매출을 먼저 등록해 주세요")
            Exit Sub
        End If
        FrmCopyIncome.Show()
    End Sub

#Region "프로시져"

    Private Function fnAddSql() As String
        Dim addQuery As String = ""
        If dpStartDt.Text <> "" Then
            addQuery = "AND A.incomeDt >= '" & dpStartDt.Text & "' "
        End If
        If dpEndDt.Text <> "" Then
            addQuery = addQuery + "AND A.incomeDt <= '" & dpEndDt.Text & "' "
        End If
        If txtSearch.Text <> "" Then
            addQuery = addQuery + " AND A.article LIKE '%" + txtSearch.Text + "%' "
        End If
        Return addQuery
    End Function

    Private Sub grid1Refresh(ByVal initFlag As String)
        Call dbConnection()
        Dim addSql As String = ""
        Dim valFindCompany As String = ""
        Dim totalAmt As Double = 0
        Dim totalOrgAmt As Double = 0
        Dim totalRestAmt As Double = 0

        '## 검색 조건에 참여하는 쿼리는 함수로 별도 관리
        addSql = fnAddSql()
        If cmbFindCompany.SelectedValue.ToString <> 0 Then
            valFindCompany = cmbFindCompany.SelectedValue.ToString
        End If
        If valFindCompany <> "" Then
            If addSql <> "" Then
                addSql = addSql + " AND "
            End If
            addSql = addSql + "A.compCd=" + valFindCompany
        End If
        dsIncome = New DataSet
        If initFlag = "default" Then
            addSql = "AND A.flag='N' "
        End If

        sql = "SELECT AA.incCd, AA.incomeDt as 거래일, AA.article as 내역, AA.accountNm as 계정, AA.amount as 총액, AA.restAmount as 미수금, AA.orgAmount as 원금, AA.tax as 부가세, CC.company as 거래처, AA.remarks as 메모 " & _
            "   FROM (" & _
            "       SELECT A.incCd, A.incomeDt, A.article, B.accountNm, A.amount, A.restAmount, A.orgAmount, A.tax, A.flag, A.compCd, A.remarks " & _
            "       FROM tblIncome A LEFT JOIN tblAccount B ON A.accountCd=B.accountCd " & _
            "       WHERE A.flag='Y'" + addSql & _
            "       ) AA LEFT JOIN tblCompany CC ON AA.compCd=CC.compCd " & _
            "    ORDER BY AA.incomeDt DESC "

        Try
            daIncome = New OleDb.OleDbDataAdapter(sql, dbConn)
            daIncome.Fill(dsIncome, "Income")

            grdIncome.DataSource = dsIncome.Tables("Income")
            lbGrid1Cnt.Text = "총 " + dsIncome.Tables("Income").Rows.Count.ToString + " 건"
            For c = 0 To dsIncome.Tables("Income").Rows.Count - 1
                totalAmt = totalAmt + CDbl(dsIncome.Tables("Income").Rows(c).Item(4))
                totalOrgAmt = totalOrgAmt + CDbl(dsIncome.Tables("Income").Rows(c).Item(6))
                totalRestAmt = totalRestAmt + CDbl(dsIncome.Tables("Income").Rows(c).Item(5))
            Next
            lbTotalAmt.Text = "총합계 : " + Format(CInt(totalAmt), "#,##0") + "   /   원금합계 : " + Format(CInt(totalOrgAmt), "#,##0")
            lbTotalRestAmt.Text = "미입금합계 : " + Format(CInt(totalRestAmt), "#,##0")

            dbConn.Close()
            Call setGrid1Design()

            If valFindCompany = "" Then
                Call grid2Refresh("")
                Call grid3Refresh("")
            End If
            'grdIncome.Columns(2).Frozen = True
        Catch err As ObjectDisposedException
            dbConn.Close()
            MsgBox(sql)

            MsgBox(err.Message, MsgBoxStyle.Critical, "오류")
        End Try
    End Sub

    Private Sub setGrid1Design()

        grdIncome.Columns(0).Visible = False
        grdIncome.Columns(1).Width = "80"
        grdIncome.Columns(2).Width = "200"
        grdIncome.Columns(3).Width = "100"

        grdIncome.Columns(4).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
        grdIncome.Columns(4).DefaultCellStyle.Format = "n0"
        grdIncome.Columns(4).Width = "80"
        grdIncome.Columns(5).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
        grdIncome.Columns(5).DefaultCellStyle.Format = "n0"
        grdIncome.Columns(5).DefaultCellStyle.ForeColor = Color.Red
        grdIncome.Columns(5).Width = "80"
        grdIncome.Columns(6).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
        grdIncome.Columns(6).DefaultCellStyle.Format = "n0"
        grdIncome.Columns(6).Width = "80"
        grdIncome.Columns(7).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
        grdIncome.Columns(7).DefaultCellStyle.Format = "n0"
        grdIncome.Columns(7).Width = "80"
        grdIncome.Columns(8).Width = "150"
        grdIncome.Columns(9).Width = "150"
        With grdIncome.DefaultCellStyle
            .Alignment = DataGridViewContentAlignment.MiddleCenter

        End With
        grdIncome.Columns(2).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft
        grdIncome.Columns(8).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft
        grdIncome.Columns(9).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft
        'grdIncome.Columns(2).Frozen = True

        gSubMkCmbFlag(cmbFlag) '## 삭제 여부 콤보박스 초기화
        cmbFlag.SelectedIndex = 0
    End Sub

    Private Sub grid2Refresh(ByVal initFlag As String)
        Call dbConnection()
        Dim addSql As String = ""

        '## 검색 조건에 참여하는 쿼리는 함수로 별도 관리
        addSql = fnAddSql()

        dsIncome = New DataSet
        If initFlag = "default" Then
            addSql = "AND A.flag='N' "
        End If

        sql = "SELECT A.compCd, B.company as 거래처, sum(A.amount) as 총금액, sum(A.restAmount) as 미입금총액, sum(A.orgAmount) as 원금총액, sum(A.tax) as 세금총액" + _
            "   FROM tblIncome a LEFT JOIN tblCompany B ON A.compCd=B.compCd " + _
            "       WHERE A.flag='Y' " + addSql + _
            "   GROUP BY  A.compCd, B.company ORDER BY B.company DESC "

        Try
            daIncome = New OleDb.OleDbDataAdapter(sql, dbConn)
            daIncome.Fill(dsIncome, "sumCompany")

            grdSumCompany.DataSource = dsIncome.Tables("sumCompany")

            dbConn.Close()
            Call setSumGridDesign(grdSumCompany)

        Catch err As ObjectDisposedException
            dbConn.Close()
            MsgBox(sql)

            MsgBox(err.Message, MsgBoxStyle.Critical, "오류")
        End Try
    End Sub

    Private Sub grid3Refresh(ByVal initFlag As String)
        Call dbConnection()
        Dim addSql As String = ""

        '## 검색 조건에 참여하는 쿼리는 함수로 별도 관리
        addSql = fnAddSql()

        If initFlag = "default" Then
            addSql = "AND A.flag='N' "
        End If
        dsIncome = New DataSet

        sql = "SELECT A.accountCd, B.accountNm as 거래처, sum(A.amount) as 총금액, sum(A.restAmount) as 미입금총액, sum(A.orgAmount) as 원금총액, sum(A.tax) as 세금총액" + _
            "   FROM tblIncome a LEFT JOIN tblAccount B ON A.accountCd=B.accountCd " + _
            "       WHERE A.flag='Y' " + addSql + _
            "   GROUP BY A.accountCd, B.accountNm ORDER BY B.accountNm DESC "

        Try
            daIncome = New OleDb.OleDbDataAdapter(sql, dbConn)
            daIncome.Fill(dsIncome, "sumAccount")

            grdSumAccount.DataSource = dsIncome.Tables("sumAccount")

            dbConn.Close()
            Call setSumGridDesign(grdSumAccount)

        Catch err As ObjectDisposedException
            dbConn.Close()
            MsgBox(sql)

            MsgBox(err.Message, MsgBoxStyle.Critical, "오류")
        End Try
    End Sub

    '## 계정별합계와 거래처별 합계 공용으로 사용
    Private Sub setSumGridDesign(ByVal obj As Object)
        obj.Columns(0).Visible = False
        obj.Columns(1).Width = "120"

        obj.Columns(5).DefaultCellStyle.Format = "n0"
        obj.Columns(5).Width = "90"
        obj.Columns(2).DefaultCellStyle.Format = "n0"
        obj.Columns(2).Width = "90"
        obj.Columns(3).DefaultCellStyle.Format = "n0"
        obj.Columns(3).Width = "90"
        obj.Columns(3).DefaultCellStyle.ForeColor = Color.Red
        obj.Columns(4).DefaultCellStyle.Format = "n0"
        obj.Columns(4).Width = "90"

        With obj.DefaultCellStyle
            .Alignment = DataGridViewContentAlignment.MiddleRight

        End With
        obj.Columns(1).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft
        'obj.Columns(1).Frozen = True
    End Sub

    '## 거래입금내역 그리드
    Private Sub grid4Refresh()
        Call dbConnection()
        Dim addSql As String = ""
        Dim valIncCd As String

        If txtIncCd.Text = "" Then
            valIncCd = "0"
        Else
            valIncCd = txtIncCd.Text
        End If

        '## 검색 조건에 참여하는 쿼리는 함수로 별도 관리
        addSql = fnAddSql()

        dsIncRs = New DataSet

        sql = "SELECT A.incRsSeq, A.actionDt as 입금일, A.amount as 입금액, B.itemNm as 입금방법, A.bankDt as 통장일" + _
            "   FROM tblIncResult A LEFT JOIN (SELECT itemNm, itemCd FROM tblComCode WHERE flag='Y' AND groupCd='0006') B ON A.incMethod=B.itemCd " + _
            "       WHERE A.flag='Y' AND A.incCd=" + valIncCd + _
            "   ORDER BY A.actionDt DESC "

        Try
            daIncRs = New OleDb.OleDbDataAdapter(sql, dbConn)
            daIncRs.Fill(dsIncRs, "INCResult")

            grdIncResult.DataSource = dsIncRs.Tables("INCResult")

            dbConn.Close()
            Call setGrid4Design()

        Catch err As ObjectDisposedException
            dbConn.Close()
            MsgBox(sql)

            MsgBox(err.Message, MsgBoxStyle.Critical, "오류")
        End Try
    End Sub

    '## 계정별합계와 거래처별 합계 공용으로 사용
    Private Sub setGrid4Design()
        grdIncResult.Columns(0).Visible = False

        grdIncResult.Columns(1).Width = "80"
        grdIncResult.Columns(2).DefaultCellStyle.Format = "n0"
        grdIncResult.Columns(2).Width = "90"
        grdIncResult.Columns(3).Width = "90"
        grdIncResult.Columns(4).Width = "80"

        With grdIncResult.DefaultCellStyle
            .Alignment = DataGridViewContentAlignment.MiddleCenter

        End With
        grdIncResult.Columns(2).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
    End Sub

    '## 매출 그리드 더블클릭
    Private Sub grdIncome_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grdIncome.CellDoubleClick
        If e.RowIndex = -1 Then
            Exit Sub
        End If
        If IsDBNull(grdIncome.Rows(e.RowIndex).Cells(0).Value) = True Then
            Exit Sub
        End If

        '## 거래내역 상세 정보 호출
        Call incomeDetail(grdIncome.Rows(e.RowIndex).Cells(0).Value)

        '## 입금내역 그리드로 호출
        Call grid4Refresh()
    End Sub

    '## 거래내역 상세 정보
    Private Sub incomeDetail(ByVal incCd As String)
        sql = "SELECT incCd, article, accountCd, amount, orgAmount, tax, compCd, incomeDt, flag, remarks  FROM tblIncome WHERE incCd=" & incCd

        Call dbConnection()
        dsIncome = New DataSet
        daIncome = New OleDb.OleDbDataAdapter(sql, dbConn)
        daIncome.Fill(dsIncome, "incomeInfo")

        dbConn.Close()

        txtReset()

        TabControl.SelectedIndex = 1
        txtIncCd.Text = dsIncome.Tables("incomeInfo").Rows(0).Item(0)
        txtArticle.Text = dsIncome.Tables("incomeInfo").Rows(0).Item(1)

        If IsDBNull(dsIncome.Tables("incomeInfo").Rows(0).Item(2)) = False Then
            cmbAccount.SelectedValue = dsIncome.Tables("incomeInfo").Rows(0).Item(2)
        End If
        If IsDBNull(dsIncome.Tables("incomeInfo").Rows(0).Item(3)) = False Then
            txtAmount.Text = dsIncome.Tables("incomeInfo").Rows(0).Item(3)
            txtAmount.Text = Format(CInt(txtAmount.Text), "#,##0")
        End If
        If IsDBNull(dsIncome.Tables("incomeInfo").Rows(0).Item(4)) = False Then
            txtOrgAmount.Text = dsIncome.Tables("incomeInfo").Rows(0).Item(4)
            txtOrgAmount.Text = Format(CInt(txtOrgAmount.Text), "#,##0")
        End If
        If IsDBNull(dsIncome.Tables("incomeInfo").Rows(0).Item(5)) = False Then
            txtTax.Text = dsIncome.Tables("incomeInfo").Rows(0).Item(5)
            txtTax.Text = Format(CInt(txtTax.Text), "#,##0")
        End If
        If IsDBNull(dsIncome.Tables("incomeInfo").Rows(0).Item(6)) = False Then
            cmbCompany.SelectedValue = dsIncome.Tables("incomeInfo").Rows(0).Item(6)
        End If
        If IsDBNull(dsIncome.Tables("incomeInfo").Rows(0).Item(7)) = False Then
            dpIncomeDt.Text = dsIncome.Tables("incomeInfo").Rows(0).Item(7)
        End If
        If IsDBNull(dsIncome.Tables("incomeInfo").Rows(0).Item(8)) = False Then
            cmbFlag.SelectedValue = dsIncome.Tables("incomeInfo").Rows(0).Item(8)
        End If
        If IsDBNull(dsIncome.Tables("incomeInfo").Rows(0).Item(9)) = False Then
            txtRemarks.Text = dsIncome.Tables("incomeInfo").Rows(0).Item(9)
        End If
    End Sub

    '## 입금내역 그리드 클릭
    Private Sub grdIncResult_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grdIncResult.CellClick
        If e.RowIndex = -1 Then
            Exit Sub
        End If
        If IsDBNull(grdIncResult.Rows(e.RowIndex).Cells(0).Value) = True Then
            Exit Sub
        End If
        sql = "SELECT IncRsSeq, amount, IncMethod, actionDt, bankDt, remarks, flag  FROM tblIncResult WHERE incRsSeq=" & grdIncResult.Rows(e.RowIndex).Cells(0).Value

        Call dbConnection()
        dsIncome = New DataSet
        daIncome = New OleDb.OleDbDataAdapter(sql, dbConn)
        daIncome.Fill(dsIncome, "incResultInfo")

        dbConn.Close()

        txtRsReset()

        txtPayRsSeq.Text = dsIncome.Tables("incResultInfo").Rows(0).Item(0)
        txtRsAmount.Text = dsIncome.Tables("incResultInfo").Rows(0).Item(1)
        txtRsAmount.Text = Format(CInt(txtRsAmount.Text), "#,##0")

        If IsDBNull(dsIncome.Tables("incResultInfo").Rows(0).Item(2)) = False Then
            cmbPayMethod.SelectedValue = dsIncome.Tables("incResultInfo").Rows(0).Item(2)
        End If
        If IsDBNull(dsIncome.Tables("incResultInfo").Rows(0).Item(3)) = False Then
            dpActionDt.Text = dsIncome.Tables("incResultInfo").Rows(0).Item(3)
        End If
        If IsDBNull(dsIncome.Tables("incResultInfo").Rows(0).Item(4)) = False Then
            dpBankDt.Text = dsIncome.Tables("incResultInfo").Rows(0).Item(4)
        End If
        If IsDBNull(dsIncome.Tables("incResultInfo").Rows(0).Item(5)) = False Then
            txtRsRemarks.Text = dsIncome.Tables("incResultInfo").Rows(0).Item(5)
        End If
        If IsDBNull(dsIncome.Tables("incResultInfo").Rows(0).Item(6)) = False Then
            cmbRsFlag.SelectedValue = dsIncome.Tables("incResultInfo").Rows(0).Item(6)
        End If
    End Sub

    '## 거래내역 저장
    Private Sub saveIncome(ByVal rsFlag As String)

        Dim oleCmd As OleDb.OleDbCommand
        Dim oleTran As OleDb.OleDbTransaction
        Dim rtnMsg As String = ""
        Dim valIncCd, valCompCd, valArticle, valAmount, valOrgAmout, valTax, valAccountCd, valIncomeDt, valFlag, valRemarks As String
        Dim curDt As DateTime = Now

        valCompCd = cmbCompany.SelectedValue.ToString
        valArticle = gFnChkVal(txtArticle.Text)
        valRemarks = gFnChkVal(txtRemarks.Text)
        valAmount = gFnChkVal(txtAmount.Text)
        valOrgAmout = gFnChkVal(txtOrgAmount.Text)
        valTax = gFnChkVal(txtTax.Text)
        valAccountCd = cmbAccount.SelectedValue.ToString
        valIncomeDt = dpIncomeDt.Text
        valIncCd = txtIncCd.Text
        valFlag = cmbFlag.SelectedValue.ToString

        If valArticle = "" Then
            MsgBox("내역을 바르게 입력해 주세요")
            txtArticle.Focus()
            dbConn.Close()
            Exit Sub
        End If
        If valAccountCd = "" Then
            MsgBox("계정을 바르게 선택해 주세요")
            cmbAccount.Focus()
            dbConn.Close()
            Exit Sub
        End If
        If valAmount = "" Then
            MsgBox("금액을 바르게 입력해 주세요")
            txtAmount.Focus()
            dbConn.Close()
            Exit Sub
        End If

        Call dbConnection()

        If txtIncCd.Text = "" Then
            valIncCd = gFnGetIncCd()
            sql = "INSERT INTO tblIncome(incCd, accountCd, article, amount, orgAmount, tax, compCd, incomeDt, restAmount, remarks, addDt, flag) " + _
                "   VALUES(" + valIncCd + ",'" + valAccountCd + "','" + valArticle + "','" + valAmount + "','" + valOrgAmout + "','" + valTax + _
                "','" + valCompCd + "','" + valIncomeDt + "','" + valAmount + "','" + valRemarks + "','" & curDt & "','" + valFlag + "')"
            rtnMsg = "매출 정보가 등록되었습니다"
        Else
            sql = "UPDATE tblIncome SET article='" + valArticle + "', accountCd='" + valAccountCd + "', amount='" + valAmount + "', orgAmount='" + valOrgAmout + "', tax='" + valTax + "', restAmount='" + valAmount + "', compCd='" + valCompCd + "', incomeDt='" + valIncomeDt + "', remarks='" + valRemarks + "', flag='" + valFlag + "', updateDt='" + curDt + "' WHERE incCd=" + valIncCd
            rtnMsg = "매출 정보가 수정되었습니다"
        End If

        oleCmd = New OleDb.OleDbCommand(sql, dbConn)

        oleTran = dbConn.BeginTransaction
        oleCmd.Transaction = oleTran
        Try

            oleCmd.ExecuteNonQuery()
            oleTran.Commit()

            dbConn.Close()
            If rsFlag = "showAnswer" Then
                MsgBox(rtnMsg)
                Call txtReset()
            ElseIf rsFlag = "allSave" Then
                Call incomeDetail(valIncCd)
            End If
        Catch err As OleDb.OleDbException
            oleTran.Rollback()
            dbConn.Close()
            MsgBox(sql)

            MsgBox(err.Message, MsgBoxStyle.Critical, "오류")
        End Try
        If rsFlag = "showAnswer" Then
            '## 잔금 다시 계산
            Call recountRestAmount(valIncCd)
            Call grid1Refresh("")
        End If
    End Sub

    '## 입금내역 저장
    Private Sub saveIncRs()

        '## 거래내역 저장 함수 호출
        Call saveIncome("")

        Call dbConnection()
        Dim oleCmd As OleDb.OleDbCommand
        Dim oleTran As OleDb.OleDbTransaction
        Dim rtnMsg As String = ""
        Dim valIncCd, valPayRsSeq, valIncMethod, valRsAmount, valActionDt, valBankDt, valRsRemarks, valRsFlag As String
        Dim curDt As DateTime = Now


        valIncMethod = cmbPayMethod.SelectedValue.ToString
        valRsRemarks = gFnChkVal(txtRsRemarks.Text)
        valIncCd = txtIncCd.Text
        valRsAmount = txtRsAmount.Text
        valActionDt = dpActionDt.Text
        valBankDt = dpBankDt.Text
        valPayRsSeq = txtPayRsSeq.Text
        valRsFlag = cmbRsFlag.SelectedValue.ToString

        If txtIncCd.Text = "" Then
            MsgBox("거래내역을 먼저 선택해 주세요")
            dbConn.Close()
            Exit Sub
        End If
        If txtRsAmount.Text = "" Then
            MsgBox("입금액을 바르게 입력해 주세요")
            txtRsAmount.Focus()
            dbConn.Close()
            Exit Sub
        End If


        If txtPayRsSeq.Text = "" Then
            sql = "INSERT INTO tblIncResult(incCd, amount, actionDt, bankDt, incMethod, remarks, flag, addDt) VALUES(" + valIncCd + ",'" + valRsAmount + "','" + valActionDt + "','" + valBankDt + "','" + valIncMethod + "','" + valRsRemarks + "','" + valRsFlag + "','" + curDt + "')"
            rtnMsg = "입금 정보가 등록되었습니다"
        Else
            sql = "UPDATE tblIncResult SET amount='" + valRsAmount + "', actionDt='" + valActionDt + "', bankDt='" + valBankDt + "', incMethod='" + valIncMethod + "', remarks='" + valRsRemarks + "', flag='" + valRsFlag + "', updateDt='" + curDt + "' WHERE incRsSeq=" + valPayRsSeq
            rtnMsg = "입금 정보가 수정되었습니다"
        End If

        oleCmd = New OleDb.OleDbCommand(sql, dbConn)

        oleTran = dbConn.BeginTransaction
        oleCmd.Transaction = oleTran
        Try

            oleCmd.ExecuteNonQuery()
            oleTran.Commit()

            dbConn.Close()
            MsgBox(rtnMsg)
        Catch err As OleDb.OleDbException
            oleTran.Rollback()
            dbConn.Close()
            MsgBox(sql)

            MsgBox(err.Message, MsgBoxStyle.Critical, "오류")
        End Try

        Call recountRestAmount(valIncCd)
        Call grid4Refresh()
        Call txtRsReset()
        Call grid1Refresh("")
    End Sub

    '## 입금 총액 적용(잔금-지급총액)
    Private Sub recountRestAmount(ByVal incCd As String)

        Dim oleCmd As OleDb.OleDbCommand
        Dim oleTran As OleDb.OleDbTransaction
        Dim incAmt As String

        incAmt = fnGetIncRs(incCd)
        Call dbConnection()

        sql = "UPDATE tblIncome SET restAmount=(restAmount-" + incAmt + ") WHERE incCd=" + incCd + " AND (restAmount-" + incAmt + ")>=0"
        oleCmd = New OleDb.OleDbCommand(sql, dbConn)

        oleTran = dbConn.BeginTransaction
        oleCmd.Transaction = oleTran
        oleCmd.ExecuteNonQuery()
        oleTran.Commit()

        dbConn.Close()
    End Sub

    '## 입금 총액 구하기
    Private Function fnGetIncRs(ByVal incCd As String) As String
        Dim incAmt As String
        Call dbConnection()
        sql = "SELECT sum(amount) as incAmt FROM tblIncResult WHERE flag='Y' AND incCd=" + incCd + " GROUP BY incCd"
        dsIncome = New DataSet
        daIncome = New OleDb.OleDbDataAdapter(sql, dbConn)
        daIncome.Fill(dsIncome, "incAmount")

        dbConn.Close()
        If dsIncome.Tables("incAmount").Rows.Count > 0 Then
            'If IsDBNull(dsIncome.Tables("incAmount").Rows(0).Item(0)) = False Then
            incAmt = dsIncome.Tables("incAmount").Rows(0).Item(0)
        Else
            incAmt = 0
        End If
        Return incAmt
    End Function

    Private Sub txtReset()
        txtIncCd.Clear()
        txtArticle.Clear()
        txtAmount.Clear()
        txtFindCompany.Clear()
        txtOrgAmount.Clear()
        txtTax.Clear()
        txtRemarks.Clear()
        cmbFlag.SelectedIndex = 0
        Call txtRsReset()
        Call grid4Refresh()
    End Sub

    Private Sub txtRsReset()
        txtRsAmount.Clear()
        txtPayRsSeq.Clear()
        txtRsRemarks.Clear()
        cmbRsFlag.SelectedIndex = 0
    End Sub

    Private Sub initForm()
        Call dbConnection()
        Dim curDt As String = Format(Now, "yyyy-MM-dd").ToString
        Dim divDt() As Object
        divDt = Split(curDt, "-")
        Dim curMnthFirst = divDt(0) + "-" + divDt(1) + "-01"

        dpStartDt.Text = curMnthFirst
        dpEndDt.Text = curDt
        dbConn.Close()
    End Sub
#End Region

End Class